<script setup lang="ts">
import 'jsoneditor/dist/jsoneditor.css'
// import formConfigModelJsonSchema from './formConfigModelJsonSchema.json'
import JSONEditor, { type JSONEditorOptions } from 'jsoneditor'
import { onMounted, ref, watchEffect } from 'vue'

const props = defineProps<{
  value?: any
}>()

const emit = defineEmits<{
  (event: 'update:value', value: any): void
}>()

const container = ref<HTMLElement | null>(null)
const options = {
  mode: 'code'
  // schema: formConfigModelJsonSchema,
  // allowSchemaSuggestions: true // 没生效
} as JSONEditorOptions

let editor: JSONEditor | null = null
const handleSetJsonValue = () => {
  if (editor) editor.set(props.value ?? {})
}

const handleSaveJsonValue = () => {
  if (editor) return emit('update:value', editor.get())
}

onMounted(() => {
  editor = new JSONEditor(container.value!, options)
  handleSetJsonValue()

  container.value?.addEventListener('keydown', (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
      e.preventDefault()
      handleSaveJsonValue()
    }
  })
})

watchEffect(() => handleSetJsonValue())
</script>

<template>
  <div
    ref="container"
    class="jsonEditorContainer"
  ></div>
</template>

<style scoped>
.jsonEditorContainer {
  height: 100%;
}
</style>

<style>
.jsoneditor-menu {
  background-color: var(--primary-bg-color);
}

.jsoneditor-poweredBy {
  display: none;
}

.jsoneditor {
  border: none;
}
</style>
